package com.ajview.core.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author ZhangJunJie
 * @Date 2022-04-27
 * <p>
 * 概要：Redis 全局配置
 */
@Configuration
@EnableCaching
public class RedisGlobalConfig {

    private Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

    /**
     * 自定义类明后不能注入
     *
     * @param lettuceConnectionFactory
     * @return
     */
    @Bean("redisTemplate")
    public RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        // 初始化RedisTemplate 模板实例
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 初始化 Jackson2JsonRedisSerializer 序列化实例

        ObjectMapper objectMapper = new ObjectMapper();

        /**
         * json序列化时，不仅是根据get方法来序列化的，而是实体类中所有的有返回值的方法都会将返回的值序列化，
         * 但是反序列化时是根据set方法来实现的，所以当实体类中有非get，set方法的方法有返回值时，反序列化时就会出错。
         * Could not read JSON: Unrecognized field “enabled”
         *
         * 例如：LoginUser实现UserDetails 中有非属性的get、set方法，反序列化是会报错
         */
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();


        //key采用String的序列化方式
        redisTemplate.setKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的key也采用String的序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        //注入连接工厂
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        // 替换默认的RedisTemplate
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
